package com.jiankangjin.alipaychannel.services.impl;


import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jiankangjin.alipaychannel.alipay.config.AlipayConfig;
import com.jiankangjin.alipaychannel.alipay.util.AlipayCore;
import com.jiankangjin.alipaychannel.services.RefundService;
import com.jiankangjin.alipaychannel.util.XmlUtil;
import com.jiankangjin.alipaychannel.vo.PayXmlBean;
import com.jiankangjin.alipaychannel.vo.RefundVo;
import com.jiankangjin.httpclient.HttpClient;

/**
 * 支付宝所有类型版本支付方法实现
 */
public class RefundServiceImpl implements RefundService {
	private static final transient Log logger = LogFactory.getLog(RefundServiceImpl.class);

	/**
	 * 支付宝条码付退款
	 */
	@Override
	public RefundVo barcode_V0_0_1(String pay_ssn_id, String order_id,
			String total_fee, String pay_chnl_seq, String refund_fee,
			String currency, String expand_json) {
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "alipay.acquire.cancel");
        sParaTemp.put("partner", AlipayConfig.PARTNER);
        sParaTemp.put("_input_charset", "utf-8");
        sParaTemp.put("alipay_ca_request", "2");
		sParaTemp.put("out_trade_no", pay_ssn_id);
		sParaTemp.put("trade_no", pay_chnl_seq);
//		sParaTemp.put("operator_type", "1");
//		sParaTemp.put("operator_id", "test-02");
		
		//用支付宝的类和SDK进行RSA签名
		String privateKey = AlipayConfig.PRIVATE_KEY;
        Map<String, String> sPara = AlipayCore.buildSignPara(sParaTemp, privateKey);
        Map<String, Object> ssPara = new HashMap<String, Object>();
        for (String key : sPara.keySet()) {
			ssPara.put(key, sPara.get(key));
		}
        logger.info("调支付宝网关退款:"+ssPara);
        HttpClient httpClient = HttpClient.getInstance();
    	String service = "https://mapi.alipay.com/gateway.do?";
    	//提交到支付宝得到XML返回数据
    	String XMLstr = httpClient.doPOSTgetStr(service, ssPara);
    	//logger.info(XMLstr);
    	//用dom4j的方式 把XML转为对象
    	PayXmlBean payXmlBean = XmlUtil.parseCreateAndPayVo(XMLstr);
    	RefundVo refundVo = new RefundVo();
    	if (payXmlBean != null && "SUCCESS".equals(payXmlBean.getResultCode())) {
    		refundVo.setRefund_status("1002");
		} else {
			refundVo.setRefund_status("0042");
		}
    	refundVo.setPay_ssn_id(pay_ssn_id);
    	refundVo.setPay_chnl_seq(pay_chnl_seq);
    	refundVo.setRefund_fee(refund_fee);
    	refundVo.setRefund_msg(payXmlBean.getDetailErrorDes());
    	refundVo.setResp_status("0000");
    	refundVo.setResp_msg("成功");
    	refundVo.setExpand_json(expand_json);
    	refundVo.setSign("AlipayChannel_refund_sign");
		return refundVo;
	}

	/**
	 * 
	 */
	@Override
	public RefundVo public_V0_0_1(String pay_ssn_id, String order_id,
			String total_fee, String pay_chnl_seq, String refund_fee,
			String currency, String expand_json) {
		return null;
	}
}